<template>
  <basic-container>
    <div class="container">
      <!--头部搜索部分-->
      <div class="merchant" style="display: inline-block">
        选择商家：
        <el-select
          filterable
          remote
          :remote-method="remoteMerchant"
          v-model="merchantId"
          @change="changeMerchant"
          placeholder="请选择"
        >
          <el-option
            v-for="(item,index) in merchantList"
            :key="index"
            :label="item.merchantName"
            @change="changeMerchant"
            :value="item.merchantId"
          />
        </el-select>
      </div>
      <div class="shop" style="display: inline-block;margin-left: 20px">
        选择店铺：
        <el-select
          filterable
          remote
          :remote-method="remoteShop"
          v-model="shopId"
          @change="changeShop"
          placeholder="请选择"
        >
          <el-option
            v-for="(item,index) in shopList"
            :key="index"
            :label="item.name"
            @change="changeShop"
            :value="item.shopId"
          />
        </el-select>
      </div>
      <div class="search-wrap">
        <el-input placeholder="请输入内容" v-model="searchText" clearable>
          <el-select v-model="searchSelect" slot="prepend" placeholder="请选择" class="search">
            <el-option label="商品编号" value="1"></el-option>
            <el-option label="商品名称" value="2"></el-option>
          </el-select>
        </el-input>
        <el-select
          v-model="modelStatus"
          slot="prepend"
          style="margin-left: 10px; width: 120px;"
          placeholder="是否启用多规格"
        >
          <el-option label="全部规格" value></el-option>
          <el-option label="多规格" value="1"></el-option>
          <el-option label="单规格" value="0"></el-option>
        </el-select>
        <el-button type="primary" size="small" @click="searchGoodsList" class="search-btn">搜索</el-button>
        <el-button type="default" size="small" @click="resetGoodsList">清除条件</el-button>
        <div class="tool-btns">
          <goods_import
            ref="goodsImport"
            style="display: inline;margin-right: 10px"
            :inputShopId="shopId"
          />
          <el-button type="primary" @click="ToAddGoods">新增商品</el-button>
          <el-button type="primary" @click="toCSale" :disabled="toSaleBtnFlag" v-show="currentMerchant.pdsType==1">一键同步商城</el-button>
        </div>
      </div>
      <el-container>
        <el-header class="header-nav">
          <el-tabs v-model="activeTab" @tab-click="changeTab" style="margin-left: 10px;">
            <el-tab-pane label="全部" name="0"></el-tab-pane>
            <el-tab-pane label="在售中" name="1"></el-tab-pane>
            <el-tab-pane label="已售罄" name="2"></el-tab-pane>
            <el-tab-pane label="已下架" name="3"></el-tab-pane>
          </el-tabs>
        </el-header>
        <el-container>
          <el-container>
            <el-aside width="220px" class="aside-nav">
              <avue-tree
                :option="categoryOption"
                :data="goodsCategories"
                @node-click="getCategoryGoods"
              ></avue-tree>
            </el-aside>
            <el-main class="goods-info-table">
              <avue-crud ref="crud"
                         :data="goodsList"
                         :option="tableOption"
                         @row-del="handleDelete"
                         :show-column.sync="currentMerchant.pdsType==1 ? showColumnAll :showColumn">
                <template slot="thumbUrl" slot-scope="scope">
                  <img width="60px" height="60px" :src="scope.row.thumbUrl" />
                </template>

                <template slot-scope="scope" slot="sort">
                  <input-box
                    :changeValue="scope.row.sort"
                    :goodsName="scope.row.goodsName"
                    :goods-id="scope.row.goodsId"
                    :type="1"
                    title="修改权重值"
                    @refresh="refresh"
                  ></input-box>
                </template>

                <template slot-scope="scope" slot="storage">
                  <input-box
                    :changeValue="scope.row.storage"
                    :goodsName="scope.row.goodsName"
                    :goods-id="scope.row.goodsId"
                    :type="2"
                    title="修改库存"
                    @refresh="refresh"
                  ></input-box>
                </template>

                <template slot-scope="scope" slot="modelPrice">
                  <div v-for="(item,index) in scope.row.modelList" :key="index">
                    <p>{{item.modelName}}：¥{{item.modelPrice}}</p>
                  </div>
                </template>

                <template slot-scope="scope" slot="isMarketable">
                  <el-switch
                    v-model="scope.row.isMarketable"
                    :disabled="marketObj[scope.row.goodsId]"
                    :active-value="'1'"
                    :inactive-value="'0'"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="marketTable(scope.row)"
                  ></el-switch>
                </template>

                <template slot-scope="scope" slot="salecFlag">
                  <el-switch
                    v-model="scope.row.salecFlag"
                    :disabled="salecObj[scope.row.goodsId]"
                    v-show="currentMerchant.pdsType==1"
                    active-value="1"
                    inactive-value="0"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="onOrOff(scope.row,scope.row.goodsId)"
                  ></el-switch>
                </template>
                <template slot-scope="scope" slot="menu">
                  <el-button type="text" icon="el-icon-edit" @click="jumpToEidt(scope.row)">编辑</el-button>
                  <el-button type="text" @click="jumpToDetail(scope.row)">详情</el-button>
                </template>
              </avue-crud>
              <el-footer style="margin-top: 10px">
                <div class="pagination">
                  <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage"
                    :page-sizes="[10, 20, 40, 60]"
                    :page-size="10"
                    background
                    :layout="layout"
                    :total="totalCount"
                  ></el-pagination>
                </div>
              </el-footer>
            </el-main>
          </el-container>
        </el-container>
      </el-container>
    </div>
    <!-- 删除提示框 -->
    <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDelete">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import router from "@/router/router";
import { toSaleC, onSale, offSale } from "../../api/salec/salecproduct";
import { fetchList as getmerchantList } from "../../api/manage/merchant";
import { fetchList } from "../../api/manage/shop";
import { getCategoryTree } from "../../api/goods/goodscategory";
import { getGoodsList } from "../../api/goods/goods";
import { delGoods, isMarketTable } from "../../api/supply/suppliergoods";

import inputBox from "../../supply/supplygoods/component/inputBox";

import { tableoption } from "../../const/crud/pds/goods/salecGoods";
import goods_import from "@/components/goods/excel_import/goods_import";
export default {
  name: "goodsList",
  components: {
    inputBox,
    goods_import
  },
  data() {
    return {
      // request数据
      goodsCategories: [],
      tableOption: tableoption,
      goodsList: [],
      /**
       * 状态, 中间变量
       */
      activeTab: "0",
      loading: true,
      multipleSelection: [],
      isDelAll: false,
      delVisible: false,
      collapse: false,
      totalCount: 10,
      currentPage: 1,
      pageSize: 10,
      layout: "total, sizes, prev, pager, next, jumper",
      categoryId: "",
      searchText: "",
      searchSelect: "2",
      windowHeight: "600",
      toSaleBtnFlag: false,
      modelStatus: "",
      menuActiveIndex: "",
      merchantList: "",
      merchantId: "",
      currentMerchant: {},
      shopList: "",
      shopId: "",
      categoryOption: {
        defaultExpandAll: true,
        addBtn: false,
        props: {
          label: "name",
          value: "id",
          children: "children"
        }
      },
      goodsId: "",
      marketObj: {},
      salecObj:{},
      showColumn:['goodsName','sort','thumbUrl','goodsSn','modelPrice','marketPrice','storage','unit','isMarketable'],
      showColumnAll: ['goodsName','sort','thumbUrl','goodsSn','modelPrice','marketPrice','storage','unit','isMarketable','salecFlag']
    };
  },
  created() {
    this.getmerchantList({ status: 2 });
    this.remoteMerchant();
    this.getHeight();
  },
  methods: {
    //表格高度
    getHeight() {
      let tableHeight = Math.max(window.innerHeight - 400, 300);
      this.tableOption.maxHeight = tableHeight + "px";
    },
    jumpToEidt(row) {
      const query = {
        res: {
          goodsSn: row.goodsSn,
          shopId: this.shopId
        }
      };
      this.$router.push({ path: "/goods/editsupplygoods", query: query });
    },
    // 详情商品
    jumpToDetail(row) {
      const query = {
        res: {
          goodsId: row.goodsId,
          shopId: row.shopId
        }
      };
      this.$router.push({ path: "/goods/detailsupplygoods", query: query });
    },
    // 新增商品
    ToAddGoods() {
      if (this.shopId == "" || this.shopId == null) {
        this.$message.error("店铺不能为空");
      } else {
        const query = {
          res: {
            shopId: this.shopId
          }
        };
        this.$router.push({ path: "/goods/addsupplygoods", query: query });
      }
    },
    /**
     * 请求方法
     */
    // 获取表格数据
    getTableData(params = {}) {
      this.marketObj = {}
      this.salecObj = {}
      let goodsStatus = "";
      if (this.activeTab === "0") {
        goodsStatus = "";
      }
      if (this.activeTab === "1") {
        goodsStatus = 0;
      }
      if (this.activeTab === "2") {
        goodsStatus = 2;
      }
      if (this.activeTab === "3") {
        goodsStatus = 1;
      }
      params.goodsStatus = goodsStatus;
      params.shopId = this.shopId;
      params.current = this.currentPage;
      params.size = params.pageSize || this.pageSize;
      params.categoryId = this.categoryId;
      params.allShow = true;
      getGoodsList(params).then(res => {
        console.log(res);
        this.totalCount = res.data.data.total;
        this.goodsList = res.data.data.records;
      });
    },
    // 获取商品分类列表
    getGoodsCategoryList(param = {}) {
      getCategoryTree({ shopId: this.shopId, allShow: true }).then(res => {
        // console.log(res.data.data);
        this.goodsCategories = res.data.data;
      });
    },
    getCategoryGoods(categoryId) {
      let params = {};
      // params.pageNo = this.currentPage
      this.categoryId = categoryId.id;
      this.loading = true;
      this.getTableData(params);
    },
    selectCategoryGoods(index, path) {
      this.menuActiveIndex = index;
      this.getCategoryGoods(index);
    },
    // 获取供应商的商家列表
    getmerchantList(param = {}) {
      getmerchantList(param).then(res => {
        // console.log(res);
        this.merchantList = res.data.data.records;
        this.merchantId =
          this.toMerchantId || res.data.data.records[0].merchantId;
        this.getShopList();
      });
    },
    remoteMerchant(name = null) {
      let query = {
        merchantName: name,
        status: 2
      };
      getmerchantList(query).then(res => {
        this.merchantList = res.data.data.records;
      });
    },
    //获取店铺列表
    getShopList() {
      let params = {};
      params.current = this.currentPage;
      params.size = this.pageSize;
      params.status = 2;
      params.merchantId = this.merchantId;
      fetchList(params).then(res => {
        console.log(res);

        this.shopList = res.data.data.records;
        console.log(this.shopList);
        this.shopId = this.toShopId || res.data.data.records[0].shopId;
        getCategoryTree({
          shopId: res.data.data.records[0].shopId,
          allShow: true
        }).then(res => {
          this.goodsCategories = res.data.data;
        });
        this.getTableData();
      });
    },
    remoteShop(name = null) {
      let params = {
        current: this.currentPage,
        size: this.pageSize,
        status: 2,
        merchantId: this.merchantId,
        name: name
      };
      fetchList(params).then(res => {
        this.shopList = res.data.data.records;
      });
    },
    //改变merchantId
    changeMerchant() {
      let that = this;
      this.merchantList.forEach(function(item, index) {
        if (item.merchantId === that.merchantId) {
          that.currentMerchant = item;
        }
      });
      console.log("currentMerchant", that.currentMerchant);
      this.categoryId = "";
      let params = {
        current: this.currentPage,
        size: this.pageSize,
        status: 2,
        merchantId: this.merchantId,
        name: name
      };
      fetchList(params).then(res => {
        console.log(res);
        if (res.data.data.records.length == 0) {
          this.$message.warning("没有店铺");
          this.shopId = "";
          this.goodsCategories = [];
          this.goodsList = [];
        }
        this.shopList = res.data.data.records;
        setTimeout(() => {
          this.shopId = this.shopList[0].shopId;
          this.getTableData();
          this.getGoodsCategoryList();
        }, 100);
      });
    },
    //改变shopID
    changeShop() {
      this.categoryId = "";
      this.getTableData();
      this.getGoodsCategoryList();
    },
    /**
     * 页面相关方法
     */
    searchGoodsList() {
      this.loading = true;
      this.menuActiveIndex = "";
      this.categoryId = "";
      let params = {};
      let searchSelect = this.searchSelect;
      if (searchSelect === "1") {
        params.goodsSn = this.searchText;
      }
      if (searchSelect === "2") {
        params.goodsName = this.searchText;
      }
      params.modelStatus = this.modelStatus;
      params.pageNo = this.currentPage;
      this.getTableData(params);
    },
    resetGoodsList() {
      this.loading = true;
      this.activeTab = "0";
      this.categoryId = "";
      this.searchText = "";
      this.modelStatus = "";
      this.searchSelect = "2";
      this.currentPage = 1;
      this.menuActiveIndex = "";
      let params = {};
      params.pageNo = this.currentPage;
      this.getTableData(params);
    },
    changeTab(tab) {
      this.activeTab = tab.name;
      this.loading = true;
      let params = {};
      let searchSelect = this.searchSelect;
      if (searchSelect === "1") {
        params.goodsSn = this.searchText;
      }
      if (searchSelect === "2") {
        params.goodsName = this.searchText;
      }
      params.pageNo = this.currentPage;
      this.getTableData(params);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleGoodsCommand(command) {
      if (command.type == "delete") {
        this.delVisible = true;
        (this.delItem = command.row), (this.delIndex = command.index);
      }
      if (command.type == "deleteAll") {
        this.delVisible = true;
        this.isDelAll = true;
      }
      if (command.type == "handleMarketable") {
        this.handleMarketable(1);
      }
      if (command.type == "handleDisMarketable") {
        this.handleMarketable(0);
      }
      if (command.type == "marketable") {
        this.changeMarketable(1, command.row.goodsSn);
      }
      if (command.type == "disMarketable") {
        this.changeMarketable(0, command.row.goodsSn);
      }
    },
    /**
     * 商品管理
     */
    //刷新
    refresh() {
      this.getTableData();
    },
    // 删除
    handleDelete(row) {
      console.log(row);
      console.warn("删除");
      const goodsId = row.goodsId;
      delGoods(goodsId).then(res => {
        this.$message.success("删除商品成功");
        this.getTableData();
      });
    },
    // 下架
    marketTable(val) {
      let marketable = "";
      console.log(val);
      this.$set(this.marketObj,val.goodsId,true)
      if (val.isMarketable == "1") {
        marketable = true;
      } else {
        marketable = false;
      }
      let params = {
        goodsId: val.goodsId,
        marketable: marketable
      };
      isMarketTable(params).then(res => {
        let _this = this
        if (val.isMarketable == "1") {
          if(res.data.data) {
            this.$message.success("上架成功");
            setTimeout(function() {
              _this.$set(_this.marketObj,val.goodsId,false)
            }, 1000);
          }else {
            val.isMarketable = '0'
            this.$set(this.marketObj,val.goodsId,false)
          }
        }
        if (val.isMarketable == "0") {
          if(res.data.data) {
            this.$message.success("下架成功");
            setTimeout(function() {
              _this.$set(_this.marketObj,val.goodsId,false)
            }, 1000);
          }else {
            val.isMarketable = '1'
            this.$set(this.marketObj,val.goodsId,false)
          }
        }

      });
    },
    /**
     * 分类
     */

    /**
     * 分页
     */
    handleSizeChange(size) {
      this.pageSize = size;
      this.getTableData();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getTableData();
    },
    /**
     * 一键添加到C端
     */
    toCSale() {
      console.log(this.shopId);
      this.toSaleBtnFlag = true;

      toSaleC({ shopId: this.shopId })
        .then(res => {
          if ((res.data.data)) {
            this.$message.success("同步成功");
            this.getTableData();
          } else {
            this.$message.error("同步失败");
          }
          this.toSaleBtnFlag = false;
        })
        .catch(err => {
          this.$message.error("同步失败");
          this.toSaleBtnFlag = false;
        });
    },
    // 单个同步成功
    on(req,i) {
      console.log(req);
      let params = {
        goodsId: req.goodsIds[0]
      };
      onSale(params).then(res => {
        let _this = this
        if ((res.data.data)) {
          this.$message.success("同步成功");
          setTimeout(function() {
            _this.$set(_this.salecObj,req.goodsIds[0],false)
          }, 1000);
        } else {
          this.$message.error("同步失败");
          this.$set(this.salecObj,req.goodsIds[0],false)
          this.goodsList[i].salecFlag = '0'
        }
      });
    },
    // 单个同步取消
    off(req,i) {
      console.log(req);
      let params = {
        goodsId: req.goodsIds[0]
      };
      console.log(params);
      offSale(params).then(res => {
        let _this = this
        if ((res.data.data)) {
          this.$message.success("取消成功");
          setTimeout(function() {
            _this.$set(_this.salecObj,req.goodsIds[0],false)
          }, 1000);
        } else {
          this.$message.error("取消失败");
          this.$set(_this.salecObj,req.goodsIds[0],false)
          this.goodsList[i].salecFlag = '1'
        }
      });
    },
    onOrOff(status, goodsId) {
      let req = {
        goodsIds: [goodsId]
      };
      this.$set(this.salecObj,goodsId,true)
      if (status.salecFlag == 0) {
        this.off(req,status.$index);
      } else if ((status.salecFlag == 1)) {
        this.on(req,status.$index);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.search {
  /*float: left;*/
  font-size: 13px;
  width: 100px;
}

.search-wrap {
  position: relative;
  text-align: left;
  padding-left: 10px;
  background-color: #fff;
  margin: 20px 0;
}

.search-btn {
  margin-left: 10px;
}

.pagination {
  text-align: center;
}
.tool-btns {
  /*float: right;*/
  /*margin-right: 30px;*/
  margin-left: 30px;
  display: inline-block;
}

.el-input-group {
  width: 25%;
}

.aside-nav {
  height: calc(100vh - 400px);
  text-align: left;
}
</style>

